<?php

/* 
	
	dkpm - a DKP management system
	
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/

	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Copyright (C) 2007 Martin Wedvich. All Rights Reserved.

	-
	
	functions.php
	This file contains all of the custom functions used by dkpm.
	Some of these are functions that I have discovered while browsing through
	various help forums, tweaked to fit dkpm's needs. I am not the original author 
	of those functions.
	
	Functions found in this file:
		get_client_ip, hash_ssha, randomize_string, timestamp, validate_ssha, 
		xhtml_if_available
		
*/

	if(!defined('dkpm')) {
		die();
	}
	
	function get_client_ip() {
		return (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : getenv('REMOTE_ADDR'));
  	}

	function hash_ssha($str) {
	 	// make a Salted SHA hash from a string
		mt_srand((double)microtime() * 1000000);
		$salt = pack('CCCC', mt_rand(), mt_rand(), mt_rand(), mt_rand()); 
		return ('{SSHA}' . base64_encode(pack('H*', sha1($str . $salt)) . $salt));
	}
	
	function randomize_string($length) {
	 	// randomize a string with a set length
		$salt = 'abchefghjkmnpqrstuvwxyz0123456789';
		srand((double)microtime() * 1000000);
		$i = 1;
		$str = '';
		while($i <= $length) {
			$num = rand() % 33;
			$temp = substr($salt, $num, 1);
			$str = $str . $temp;
			$i++;
		}
		return $str;
	}
	
	function timestamp($thetime) {
	 	// turn a database timestamp into a Unix one for use with the date() function
		$d = explode('-', substr($thetime, 0, 10)); // year, month, day
	 	$t = explode(':', substr($thetime, 10)); // hours, minutes, seconds
	 	return mktime($t[0], $t[1], $t[2], $d[1], $d[2], $d[0]);
	}

	function validate_ssha($hash, $str) {
	 	// validate a string with a Salted SHA hash
		$ohash = base64_decode(substr($hash, 6));
		$osalt = substr($ohash, 20);
		$ohash = substr($ohash, 0, 20);
		$nhash = pack("H*", sha1($str . $osalt));
		return ($ohash == $nhash);
	}
	
	function xhtml_if_available() {	
	 	// check if the browser supports XHTML parsing, and enable it accordingly
		if(isset($_SERVER['HTTP_ACCEPT']) && isset($_SERVER['HTTP_USER_AGENT'])) {
			if(stristr($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') || stristr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')) {
				header('Content-Type: application/xhtml+xml');
			}
		}
	}

?>